//
//  ABWebView.swift
//  ABWeb
//
//  Created by FaiWong on 2023/2/26.
//

import UIKit
import WebKit
import ABExtension
public protocol ABWebViewDelegate: NSObjectProtocol {
    func abWebView(contentSizeChanged contentSize:CGSize)
}
public class ABWebView: UIView {

    public var webView:WKWebView!
    public var adjustContentSize:Bool = true
    public weak var delegate:ABWebViewDelegate?
    public override init(frame: CGRect) {
        super.init(frame: frame)
        
        let script = "var meta = document.createElement('meta');meta.name = 'viewport';"
        "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';var head = document.getElementsByTagName('head')[0];head.appendChild(meta);document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';";
        
        let usreScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        
        let conf = WKWebViewConfiguration()
        conf.userContentController.addUserScript(usreScript)
        webView = WKWebView(frame: self.bounds, configuration: conf)
        webView.navigationDelegate = self
        self.addSubview(self.webView)
        
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public func loadHTMLString(str:String) {
        let header = "<head><meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\"><style>body,html{width: 100%;height: 100%;}*{margin:0;padding:0;}img{max-width:100%;min-width:100%;display:block; width:auto; height:auto;}</style></head>"
        let htmlStr = "<html>\(header)<body>\(str)</body></html>"
        self.webView.loadHTMLString(htmlStr, baseURL: nil)

    }
    
    public func loadUrl(loadURL:String) {
        let encodingURl = loadURL
        
        if loadURL.hasPrefix("http") {
            if let url = URL(string: encodingURl) {
                webView.load(URLRequest(url: url))
            }
        }else{
            let url = URL(fileURLWithPath: loadURL)
            webView.load(URLRequest(url: url))
        }
    
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        webView.frame = self.bounds
    }
    
    public func listenContenSize() {
        self.webView.addObserver(self, forKeyPath: "scrollView.contentSize", options: .new, context: nil)
    }
    
    
    public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "scrollView.contentSize" {
            self.delegate?.abWebView(contentSizeChanged: self.webView.scrollView.contentSize)
            if adjustContentSize {
                let webViewContentHeight = self.webView.scrollView.contentSize.height
            
                let webViewHeight = min(webViewContentHeight, self.frame.size.height)
    
                self.webView.height_ab = webViewHeight
            }

        }
    }
    
    public func setContentOffsetY(val:CGFloat) {
        self.webView.scrollView.contentOffset = CGPoint(x: 0, y: val)
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "scrollView.contentSize")
    }
}

extension ABWebView: WKNavigationDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    
    public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error)
    }
    
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(error)
    }

}
